<template>
  <div class="space-y-6">
    <!-- 页面标题和操作 -->
    <div class="flex flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
      <div>
        <h2 class="text-2xl font-bold">文章管理</h2>
        <p class="text-gray-500 mt-1">管理网站所有栏目下的文章，支持发布、编辑和删除操作</p>
      </div>
      
      <div class="flex flex-wrap gap-3">
        <button class="btn btn-secondary" @click="refreshArticles">
          <i class="fa fa-refresh"></i>
          <span>刷新</span>
        </button>
        <button class="btn btn-primary" @click="showAddArticleDialog">
          <i class="fa fa-plus"></i>
          <span>新增文章</span>
        </button>
        <button class="btn btn-secondary" @click="batchOperation('export')" :disabled="selectedArticleIds.length === 0">
          <i class="fa fa-download"></i>
          <span>导出</span>
        </button>
        <button class="btn btn-danger" @click="batchOperation('delete')" :disabled="selectedArticleIds.length === 0">
          <i class="fa fa-trash"></i>
          <span>批量删除</span>
        </button>
      </div>
    </div>
    
    <!-- 文章筛选 -->
    <div class="card p-4">
      <div class="grid grid-cols-1 md:grid-cols-4 gap-4">
        <div>
          <label class="block text-sm font-medium text-gray-700 mb-1">所属站点</label>
          <select class="form-input" v-model="filters.siteId" @change="loadArticles">
            <option value="">全部站点</option>
            <option v-for="site in sites" :key="site.id" :value="site.id">{{ site.name }}</option>
          </select>
        </div>
        <div>
          <label class="block text-sm font-medium text-gray-700 mb-1">所属栏目</label>
          <select class="form-input" v-model="filters.categoryId" @change="filterArticles">
            <option value="">全部栏目</option>
            <option 
              v-for="category in filteredCategories" 
              :key="category.id" 
              :value="category.id"
            >
              {{ getCategoryIndent(category.level) }}{{ category.name }}
            </option>
          </select>
        </div>
        <div>
          <label class="block text-sm font-medium text-gray-700 mb-1">文章状态</label>
          <select class="form-input" v-model="filters.status" @change="filterArticles">
            <option value="">全部状态</option>
            <option value="draft">草稿</option>
            <option value="pending">待审核</option>
            <option value="published">已发布</option>
            <option value="rejected">已驳回</option>
          </select>
        </div>
        <div>
          <label class="block text-sm font-medium text-gray-700 mb-1">关键词搜索</label>
          <div class="relative">
            <input 
              type="text" 
              class="form-input pl-10" 
              placeholder="标题或内容关键词"
              v-model="filters.keyword"
              @keyup.enter="filterArticles"
            >
            <i class="fa fa-search absolute left-3 top-1/2 -translate-y-1/2 text-gray-400"></i>
          </div>
        </div>
      </div>
      
      <div class="mt-4 grid grid-cols-1 md:grid-cols-3 gap-4">
        <div>
          <label class="block text-sm font-medium text-gray-700 mb-1">发布时间范围</label>
          <div class="flex gap-2">
            <input type="date" class="form-input" v-model="filters.startDate">
            <span class="flex items-center text-gray-500">至</span>
            <input type="date" class="form-input" v-model="filters.endDate">
          </div>
        </div>
        <div>
          <label class="block text-sm font-medium text-gray-700 mb-1">作者</label>
          <select class="form-input" v-model="filters.authorId" @change="filterArticles">
            <option value="">全部作者</option>
            <option v-for="author in authors" :key="author.id" :value="author.id">{{ author.name }}</option>
          </select>
        </div>
        <div class="flex items-end">
          <button class="btn btn-primary w-full" @click="filterArticles">
            <i class="fa fa-search"></i>
            <span>搜索</span>
          </button>
        </div>
      </div>
    </div>
    
    <!-- 文章列表 -->
    <div class="card">
      <div class="overflow-x-auto">
        <table class="w-full">
          <thead>
            <tr class="bg-gray-50">
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider w-12">
                <input 
                  type="checkbox" 
                  class="rounded border-gray-300 text-primary focus:ring-primary"
                  v-model="selectAll"
                  @change="handleSelectAll"
                >
              </th>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">标题</th>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">所属栏目</th>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">作者</th>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">发布时间</th>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">阅读量</th>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">状态</th>
              <th class="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider">操作</th>
            </tr>
          </thead>
          <tbody class="bg-white divide-y divide-gray-200">
            <tr v-for="article in paginatedArticles" :key="article.id" class="hover:bg-gray-50 transition-colors">
              <td class="px-6 py-4 whitespace-nowrap">
                <input 
                  type="checkbox" 
                  class="rounded border-gray-300 text-primary focus:ring-primary"
                  v-model="selectedArticleIds"
                  :value="article.id"
                >
              </td>
              <td class="px-6 py-4 whitespace-nowrap max-w-md">
                <div class="flex items-start gap-3">
                  <img 
                    v-if="article.coverImage" 
                    :src="article.coverImage" 
                    :alt="article.title"
                    class="w-16 h-12 object-cover rounded flex-shrink-0"
                  >
                  <div>
                    <div class="font-medium text-gray-900 hover:text-primary line-clamp-2" @click="viewArticle(article.id)">
                      {{ article.title }}
                    </div>
                    <div class="flex items-center gap-2 mt-1">
                      <span v-if="article.isTop" class="badge bg-warning/10 text-warning text-xs">置顶</span>
                      <span v-if="article.isRecommend" class="badge bg-success/10 text-success text-xs">推荐</span>
                      <span class="text-xs text-gray-500">{{ formatDate(article.updateTime) }}</span>
                    </div>
                  </div>
                </div>
              </td>
              <td class="px-6 py-4 whitespace-nowrap">
                <span class="text-sm text-gray-900">{{ findCategoryName(article.categoryId) }}</span>
              </td>
              <td class="px-6 py-4 whitespace-nowrap">
                <div class="flex items-center gap-2">
                  <img 
                    :src="article.authorAvatar" 
                    :alt="article.authorName"
                    class="w-6 h-6 rounded-full object-cover"
                  >
                  <span class="text-sm text-gray-900">{{ article.authorName }}</span>
                </div>
              </td>
              <td class="px-6 py-4 whitespace-nowrap">
                <span class="text-sm text-gray-900">{{ formatDate(article.publishTime || article.createTime) }}</span>
              </td>
              <td class="px-6 py-4 whitespace-nowrap">
                <span class="text-sm text-gray-900">{{ article.viewCount }}</span>
              </td>
              <td class="px-6 py-4 whitespace-nowrap">
                <span 
                  class="badge"
                  :class="getStatusBadgeClass(article.status)"
                >
                  {{ getStatusName(article.status) }}
                </span>
              </td>
              <td class="px-6 py-4 whitespace-nowrap text-right text-sm font-medium">
                <div class="flex justify-end gap-2">
                  <button 
                    class="text-primary hover:text-primary/80"
                    @click="previewArticle(article.id)"
                  >
                    预览
                  </button>
                  <button 
                    class="text-gray-600 hover:text-gray-900"
                    @click="showEditArticleDialog(article.id)"
                  >
                    编辑
                  </button>
                  <button 
                    class="text-danger hover:text-danger/80"
                    @click="confirmDeleteArticle(article.id)"
                  >
                    删除
                  </button>
                </div>
              </td>
            </tr>
            
            <tr v-if="filteredArticles.length === 0">
              <td colspan="8" class="px-6 py-12 text-center">
                <div class="inline-flex items-center justify-center w-16 h-16 rounded-full bg-gray-100 mb-4">
                  <i class="fa fa-file-text-o text-2xl text-gray-400"></i>
                </div>
                <h3 class="text-lg font-medium mb-2">未找到文章</h3>
                <p class="text-gray-500 max-w-md mx-auto">
                  没有找到符合当前筛选条件的文章，请尝试调整筛选条件或点击"新增文章"创建
                </p>
              </td>
            </tr>
          </tbody>
        </table>
      </div>
      
      <!-- 分页 -->
      <div v-if="filteredArticles.length > 0" class="px-6 py-4 border-t border-gray-200 flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
        <div class="text-sm text-gray-500">
          显示 {{ Math.min((currentPage-1)*pageSize + 1, filteredArticles.length) }} - {{ Math.min(currentPage*pageSize, filteredArticles.length) }} 条，共 {{ filteredArticles.length }} 条文章
        </div>
        <div class="flex items-center gap-2">
          <div class="text-sm">
            每页显示
            <select 
              class="ml-1 border border-gray-300 rounded px-2 py-1 text-sm"
              v-model="pageSize"
              @change="handlePageSizeChange"
            >
              <option value="10">10</option>
              <option value="20">20</option>
              <option value="50">50</option>
              <option value="100">100</option>
            </select>
            条
          </div>
          
          <div class="flex items-center gap-1">
            <button 
              class="w-8 h-8 flex items-center justify-center rounded border border-gray-300 text-gray-500 hover:bg-gray-50 disabled:opacity-50"
              :disabled="currentPage === 1"
              @click="currentPage = currentPage - 1"
            >
              <i class="fa fa-chevron-left text-xs"></i>
            </button>
            
            <button 
              v-for="page in visiblePages" 
              :key="page"
              class="w-8 h-8 flex items-center justify-center rounded"
              :class="currentPage === page ? 'bg-primary text-white' : 'border border-gray-300 hover:bg-gray-50'"
              @click="currentPage = page"
            >
              {{ page }}
            </button>
            
            <button 
              class="w-8 h-8 flex items-center justify-center rounded border border-gray-300 text-gray-500 hover:bg-gray-50 disabled:opacity-50"
              :disabled="currentPage === totalPages"
              @click="currentPage = currentPage + 1"
            >
              <i class="fa fa-chevron-right text-xs"></i>
            </button>
          </div>
          
          <div class="text-sm">
            跳至
            <input 
              type="number" 
              class="ml-1 border border-gray-300 rounded px-2 py-1 text-sm w-16 text-center"
              v-model="jumpPage"
              :min="1"
              :max="totalPages"
              @keyup.enter="handleJumpPage"
            >
            页
          </div>
        </div>
      </div>
    </div>
  </div>
  
  <!-- 新增/编辑文章对话框 -->
  <teleport to="body">
    <div class="fixed inset-0 bg-black bg-opacity-50 z-50 flex items-center justify-center p-4" v-if="articleDialogVisible">
      <div class="bg-white rounded-xl w-full max-w-4xl max-h-[90vh] overflow-y-auto">
        <div class="p-6 border-b border-gray-100 flex justify-between items-center">
          <h3 class="text-xl font-bold">{{ isEditMode ? '编辑文章' : '新增文章' }}</h3>
          <button class="text-gray-400 hover:text-gray-600" @click="closeArticleDialog">
            <i class="fa fa-times"></i>
          </button>
        </div>
        
        <div class="p-6 space-y-6">
          <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-1">文章标题 <span class="text-danger">*</span></label>
              <input 
                type="text" 
                class="form-input" 
                v-model="articleForm.title"
                placeholder="请输入文章标题"
              >
            </div>
            
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-1">所属站点 <span class="text-danger">*</span></label>
              <select class="form-input" v-model="articleForm.siteId" @change="handleSiteChange">
                <option value="">请选择站点</option>
                <option v-for="site in sites" :key="site.id" :value="site.id">{{ site.name }}</option>
              </select>
            </div>
            
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-1">所属栏目 <span class="text-danger">*</span></label>
              <select class="form-input" v-model="articleForm.categoryId">
                <option value="">请选择栏目</option>
                <option 
                  v-for="category in articleForm.siteId ? getSiteCategories(articleForm.siteId) : []" 
                  :key="category.id" 
                  :value="category.id"
                >
                  {{ getCategoryIndent(category.level) }}{{ category.name }}
                </option>
              </select>
            </div>
            
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-1">作者</label>
              <select class="form-input" v-model="articleForm.authorId">
                <option value="">请选择作者</option>
                <option v-for="author in authors" :key="author.id" :value="author.id">{{ author.name }}</option>
              </select>
            </div>
            
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-1">封面图片</label>
              <div class="mt-1 flex justify-center px-6 pt-5 pb-6 border-2 border-gray-300 border-dashed rounded-lg">
                <div class="space-y-1 text-center">
                  <i class="fa fa-cloud-upload text-gray-400 text-3xl"></i>
                  <div class="flex text-sm text-gray-600">
                    <label for="file-upload" class="relative cursor-pointer rounded-md bg-white text-primary focus-within:outline-none">
                      <span>上传图片</span>
                      <input id="file-upload" name="file-upload" type="file" class="sr-only" accept="image/*">
                    </label>
                    <p class="pl-1">或拖放文件</p>
                  </div>
                  <p class="text-xs text-gray-500">支持 PNG, JPG, GIF 格式</p>
                </div>
              </div>
              <div v-if="articleForm.coverImage" class="mt-2">
                <img :src="articleForm.coverImage" alt="封面预览" class="h-32 object-cover rounded">
              </div>
            </div>
            
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-1">文章状态 <span class="text-danger">*</span></label>
              <select class="form-input" v-model="articleForm.status">
                <option value="draft">草稿</option>
                <option value="pending">待审核</option>
                <option value="published">已发布</option>
              </select>
            </div>
          </div>
          
          <div>
            <label class="block text-sm font-medium text-gray-700 mb-1">文章摘要</label>
            <textarea 
              class="form-input h-24" 
              v-model="articleForm.summary"
              placeholder="请输入文章摘要，将显示在列表页"
            ></textarea>
          </div>
          
          <div>
            <label class="block text-sm font-medium text-gray-700 mb-1">文章内容 <span class="text-danger">*</span></label>
            <!-- 简化的编辑器示例，实际项目中可集成TinyMCE、CKEditor等 -->
            <div class="border border-gray-300 rounded-lg overflow-hidden">
              <div class="bg-gray-50 px-4 py-2 border-b border-gray-300 flex gap-2 flex-wrap">
                <button class="p-1 hover:bg-gray-200 rounded" title="加粗"><i class="fa fa-bold"></i></button>
                <button class="p-1 hover:bg-gray-200 rounded" title="斜体"><i class="fa fa-italic"></i></button>
                <button class="p-1 hover:bg-gray-200 rounded" title="下划线"><i class="fa fa-underline"></i></button>
                <span class="h-4 border-r border-gray-300"></span>
                <button class="p-1 hover:bg-gray-200 rounded" title="左对齐"><i class="fa fa-align-left"></i></button>
                <button class="p-1 hover:bg-gray-200 rounded" title="居中对齐"><i class="fa fa-align-center"></i></button>
                <button class="p-1 hover:bg-gray-200 rounded" title="右对齐"><i class="fa fa-align-right"></i></button>
                <span class="h-4 border-r border-gray-300"></span>
                <button class="p-1 hover:bg-gray-200 rounded" title="插入图片"><i class="fa fa-image"></i></button>
                <button class="p-1 hover:bg-gray-200 rounded" title="插入链接"><i class="fa fa-link"></i></button>
                <button class="p-1 hover:bg-gray-200 rounded" title="插入表格"><i class="fa fa-table"></i></button>
              </div>
              <textarea 
                class="form-input border-0 rounded-none min-h-[300px]" 
                v-model="articleForm.content"
                placeholder="请输入文章内容..."
              ></textarea>
            </div>
          </div>
          
          <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-1">SEO标题</label>
              <input 
                type="text" 
                class="form-input" 
                v-model="articleForm.seoTitle"
                placeholder="用于搜索引擎显示的标题，不填则使用文章标题"
              >
            </div>
            
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-1">SEO关键词</label>
              <input 
                type="text" 
                class="form-input" 
                v-model="articleForm.seoKeywords"
                placeholder="多个关键词用逗号分隔"
              >
            </div>
            
            <div class="md:col-span-2">
              <label class="block text-sm font-medium text-gray-700 mb-1">SEO描述</label>
              <textarea 
                class="form-input h-16" 
                v-model="articleForm.seoDescription"
                placeholder="用于搜索引擎显示的描述信息"
              ></textarea>
            </div>
          </div>
          
          <div class="flex items-center gap-3">
            <label class="inline-flex items-center">
              <input 
                type="checkbox" 
                class="rounded border-gray-300 text-primary focus:ring-primary"
                v-model="articleForm.isTop"
              >
              <span class="ml-2 text-sm text-gray-700">置顶文章</span>
            </label>
            <label class="inline-flex items-center">
              <input 
                type="checkbox" 
                class="rounded border-gray-300 text-primary focus:ring-primary"
                v-model="articleForm.isRecommend"
              >
              <span class="ml-2 text-sm text-gray-700">推荐文章</span>
            </label>
            <label class="inline-flex items-center">
              <input 
                type="checkbox" 
                class="rounded border-gray-300 text-primary focus:ring-primary"
                v-model="articleForm.allowComment"
              >
              <span class="ml-2 text-sm text-gray-700">允许评论</span>
            </label>
          </div>
        </div>
        
        <div class="p-6 border-t border-gray-100 flex justify-end gap-3">
          <button class="btn btn-secondary" @click="closeArticleDialog">
            <i class="fa fa-times"></i>
            <span>取消</span>
          </button>
          <button class="btn btn-primary" @click="saveArticle">
            <i class="fa fa-check"></i>
            <span>{{ articleForm.status === 'published' ? '发布' : '保存' }}</span>
          </button>
        </div>
      </div>
    </div>
  </teleport>
  
  <!-- 删除确认对话框 -->
  <teleport to="body">
    <div class="fixed inset-0 bg-black bg-opacity-50 z-50 flex items-center justify-center p-4" v-if="deleteDialogVisible">
      <div class="bg-white rounded-xl w-full max-w-md">
        <div class="p-6 text-center">
          <div class="w-16 h-16 rounded-full bg-danger/10 flex items-center justify-center mx-auto mb-4">
            <i class="fa fa-exclamation-triangle text-2xl text-danger"></i>
          </div>
          <h3 class="text-xl font-bold mb-2">确认删除</h3>
          <p class="text-gray-500">
            您确定要删除这{{ deleteBatch ? '些' : '篇' }}文章吗？删除后将无法恢复。
          </p>
        </div>
        
        <div class="p-4 border-t border-gray-100 flex justify-center gap-3">
          <button class="btn btn-secondary" @click="deleteDialogVisible = false">
            <i class="fa fa-times"></i>
            <span>取消</span>
          </button>
          <button class="btn btn-danger" @click="deleteConfirmed">
            <i class="fa fa-trash"></i>
            <span>确认删除</span>
          </button>
        </div>
      </div>
    </div>
  </teleport>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import {formatDate} from '@/utils/date'
const router = useRouter()

// 站点数据
const sites = ref([
  { id: 1, name: '时尚服装商城' },
  { id: 2, name: '科技有限公司官网' },
  { id: 3, name: '教育培训平台' }
])

// 栏目数据
const categories = ref([
  { id: 1, name: '首页', type: 'page', parentId: 0, siteId: 1, level: 0 },
  { id: 2, name: '产品中心', type: 'product', parentId: 0, siteId: 1, level: 0 },
  { id: 3, name: '男装系列', type: 'product', parentId: 2, siteId: 1, level: 1 },
  { id: 6, name: '品牌故事', type: 'article', parentId: 0, siteId: 1, level: 0 },
  { id: 7, name: '企业动态', type: 'article', parentId: 6, siteId: 1, level: 1 },
  { id: 9, name: '官网首页', type: 'page', parentId: 0, siteId: 2, level: 0 },
  { id: 10, name: '公司新闻', type: 'article', parentId: 0, siteId: 2, level: 0 },
  { id: 11, name: '行业资讯', type: 'article', parentId: 0, siteId: 2, level: 0 },
  { id: 12, name: '课程信息', type: 'article', parentId: 0, siteId: 3, level: 0 },
  { id: 13, name: '教学动态', type: 'article', parentId: 0, siteId: 3, level: 0 }
])

// 作者数据
const authors = ref([
  { id: 1, name: '张编辑', avatar: 'https://picsum.photos/id/1005/100/100' },
  { id: 2, name: '李记者', avatar: 'https://picsum.photos/id/1012/100/100' },
  { id: 3, name: '王小编', avatar: 'https://picsum.photos/id/1025/100/100' }
])

// 文章数据
const articles = ref([
  {
    id: 1,
    title: '2023年夏季服装流行趋势预测',
    categoryId: 7,
    siteId: 1,
    authorId: 1,
    authorName: '张编辑',
    authorAvatar: 'https://picsum.photos/id/1005/100/100',
    coverImage: 'https://picsum.photos/id/64/800/400',
    summary: '本文详细分析了2023年夏季服装的流行趋势，包括颜色、面料和款式等方面的预测。',
    content: '<p>2023年夏季，服装流行趋势将呈现多元化发展...</p>',
    status: 'published',
    isTop: true,
    isRecommend: true,
    allowComment: true,
    viewCount: 1256,
    commentCount: 32,
    createTime: '2023-05-10',
    updateTime: '2023-05-15',
    publishTime: '2023-05-15',
    seoTitle: '2023夏季服装流行趋势 - 最新预测',
    seoKeywords: '2023夏季,服装趋势,流行预测',
    seoDescription: '了解2023年夏季服装的最新流行趋势，提前把握时尚脉搏。'
  },
  {
    id: 2,
    title: '如何选择适合自己的夏季面料',
    categoryId: 7,
    siteId: 1,
    authorId: 2,
    authorName: '李记者',
    authorAvatar: 'https://picsum.photos/id/1012/100/100',
    coverImage: 'https://picsum.photos/id/96/800/400',
    summary: '夏季面料的选择直接影响穿着舒适度，本文介绍了几种常见夏季面料的特点和适用场景。',
    content: '<p>夏季气温高，选择合适的面料至关重要...</p>',
    status: 'published',
    isTop: false,
    isRecommend: true,
    allowComment: true,
    viewCount: 876,
    commentCount: 18,
    createTime: '2023-05-12',
    updateTime: '2023-05-12',
    publishTime: '2023-05-12',
    seoTitle: '夏季面料选择指南 - 舒适透气材质推荐',
    seoKeywords: '夏季面料,透气材质,面料选择',
    seoDescription: '夏季如何选择舒适透气的面料？本文为您详细介绍各种面料的特点和适用场景。'
  },
  {
    id: 3,
    title: '公司新品发布会圆满成功',
    categoryId: 10,
    siteId: 2,
    authorId: 3,
    authorName: '王小编',
    authorAvatar: 'https://picsum.photos/id/1025/100/100',
    coverImage: 'https://picsum.photos/id/26/800/400',
    summary: '我公司于5月20日举行的新品发布会取得圆满成功，多款创新产品受到市场关注。',
    content: '<p>5月20日，我公司在国际会展中心举行了年度新品发布会...</p>',
    status: 'published',
    isTop: true,
    isRecommend: true,
    allowComment: true,
    viewCount: 2156,
    commentCount: 45,
    createTime: '2023-05-21',
    updateTime: '2023-05-21',
    publishTime: '2023-05-21',
    seoTitle: '科技公司新品发布会成功举办 - 多款创新产品亮相',
    seoKeywords: '新品发布,科技产品,公司动态',
    seoDescription: '科技有限公司新品发布会圆满成功，多款创新产品受到行业和媒体的高度关注。'
  },
  {
    id: 4,
    title: '人工智能在教育领域的应用前景',
    categoryId: 13,
    siteId: 3,
    authorId: 1,
    authorName: '张编辑',
    authorAvatar: 'https://picsum.photos/id/1005/100/100',
    coverImage: '',
    summary: '本文探讨了人工智能技术在教育领域的应用现状和未来发展前景。',
    content: '<p>随着人工智能技术的快速发展，其在教育领域的应用也越来越广泛...</p>',
    status: 'draft',
    isTop: false,
    isRecommend: false,
    allowComment: true,
    viewCount: 0,
    commentCount: 0,
    createTime: '2023-06-01',
    updateTime: '2023-06-02',
    publishTime: null,
    seoTitle: '',
    seoKeywords: '',
    seoDescription: ''
  },
  {
    id: 5,
    title: '2023年度教育行业发展报告',
    categoryId: 13,
    siteId: 3,
    authorId: 2,
    authorName: '李记者',
    authorAvatar: 'https://picsum.photos/id/1012/100/100',
    coverImage: 'https://picsum.photos/id/42/800/400',
    summary: '本报告基于行业数据，分析了2023年度教育行业的发展现状和未来趋势。',
    content: '<p>2023年，教育行业面临着新的机遇和挑战...</p>',
    status: 'pending',
    isTop: false,
    isRecommend: true,
    allowComment: true,
    viewCount: 0,
    commentCount: 0,
    createTime: '2023-06-05',
    updateTime: '2023-06-05',
    publishTime: null,
    seoTitle: '2023教育行业发展报告 - 现状与趋势分析',
    seoKeywords: '教育行业,发展报告,2023趋势',
    seoDescription: '2023年度教育行业发展报告，全面分析行业现状和未来发展趋势。'
  },
  {
    id: 6,
    title: '夏季男装搭配技巧',
    categoryId: 3,
    siteId: 1,
    authorId: 3,
    authorName: '王小编',
    authorAvatar: 'https://picsum.photos/id/1025/100/100',
    coverImage: 'https://picsum.photos/id/100/800/400',
    summary: '掌握这些夏季男装搭配技巧，让你在炎热的夏天也能保持时尚感。',
    content: '<p>夏季男装搭配需要兼顾时尚与舒适...</p>',
    status: 'published',
    isTop: false,
    isRecommend: false,
    allowComment: true,
    viewCount: 632,
    commentCount: 12,
    createTime: '2023-06-08',
    updateTime: '2023-06-08',
    publishTime: '2023-06-08',
    seoTitle: '夏季男装搭配技巧 - 时尚舒适两不误',
    seoKeywords: '夏季男装,搭配技巧,时尚指南',
    seoDescription: '夏季男装如何搭配？本文分享实用搭配技巧，让你时尚又舒适。'
  }
])

// 筛选条件
const filters = reactive({
  siteId: '',
  categoryId: '',
  status: '',
  keyword: '',
  startDate: '',
  endDate: '',
  authorId: ''
})

// 分页相关
const currentPage = ref(1)
const pageSize = ref(10)
const jumpPage = ref(1)
const selectAll = ref(false)
const selectedArticleIds = ref([])

// 对话框状态
const articleDialogVisible = ref(false)
const isEditMode = ref(false)
const currentEditingId = ref(null)
const deleteDialogVisible = ref(false)
const deleteBatch = ref(false)
const deleteArticleIds = ref([])

// 文章表单数据
const articleForm = reactive({
  title: '',
  siteId: '',
  categoryId: '',
  authorId: '',
  coverImage: '',
  summary: '',
  content: '',
  status: 'draft',
  isTop: false,
  isRecommend: false,
  allowComment: true,
  seoTitle: '',
  seoKeywords: '',
  seoDescription: ''
})

// 筛选后的文章列表
const filteredArticles = computed(() => {
  return articles.value.filter(article => {
    // 站点筛选
    if (filters.siteId && article.siteId != filters.siteId) return false
    
    // 栏目筛选
    if (filters.categoryId && article.categoryId != filters.categoryId) return false
    
    // 状态筛选
    if (filters.status && article.status != filters.status) return false
    
    // 关键词筛选
    if (filters.keyword) {
      const keyword = filters.keyword.toLowerCase()
      if (!article.title.toLowerCase().includes(keyword) && 
          !(article.summary && article.summary.toLowerCase().includes(keyword)) &&
          !(article.content && article.content.toLowerCase().includes(keyword))) {
        return false
      }
    }
    
    // 作者筛选
    if (filters.authorId && article.authorId != filters.authorId) return false
    
    // 日期范围筛选
    const articleDate = article.publishTime || article.createTime
    if (filters.startDate && articleDate < filters.startDate) return false
    if (filters.endDate && articleDate > filters.endDate) return false
    
    return true
  })
})

// 分页后的文章列表
const paginatedArticles = computed(() => {
  const startIndex = (currentPage.value - 1) * pageSize.value
  return filteredArticles.value.slice(startIndex, startIndex + pageSize.value)
})

// 总页数
const totalPages = computed(() => {
  return Math.ceil(filteredArticles.value.length / pageSize.value) || 1
})

// 可见页码
const visiblePages = computed(() => {
  const pages = []
  const maxVisible = 5
  let startPage = Math.max(1, currentPage.value - Math.floor(maxVisible / 2))
  const endPage = Math.min(totalPages.value, startPage + maxVisible - 1)
  
  // 调整起始页，确保显示足够的页码
  if (endPage - startPage + 1 < maxVisible) {
    startPage = Math.max(1, endPage - maxVisible + 1)
  }
  
  for (let i = startPage; i <= endPage; i++) {
    pages.push(i)
  }
  
  return pages
})

// 筛选后的栏目列表（根据选中的站点）
const filteredCategories = computed(() => {
  if (!filters.siteId) return []
  return categories.value.filter(cat => cat.siteId == filters.siteId)
})

// 初始化
onMounted(() => {
  jumpPage.value = 1
})

// 加载文章（模拟API调用）
const loadArticles = () => {
  // 实际项目中这里会调用API加载指定站点的文章
  currentPage.value = 1
  selectedArticleIds.value = []
  selectAll.value = false
}

// 筛选文章
const filterArticles = () => {
  currentPage.value = 1
  selectedArticleIds.value = []
  selectAll.value = false
}

// 刷新文章
const refreshArticles = () => {
  // 实际项目中这里会调用API刷新文章数据
  selectedArticleIds.value = []
  selectAll.value = false
}

// 全选/取消全选
const handleSelectAll = () => {
  if (selectAll.value) {
    selectedArticleIds.value = paginatedArticles.value.map(article => article.id)
  } else {
    selectedArticleIds.value = []
  }
}

// 处理分页大小变化
const handlePageSizeChange = () => {
  currentPage.value = 1
  jumpPage.value = 1
}

// 处理页码跳转
const handleJumpPage = () => {
  let page = parseInt(jumpPage.value)
  if (isNaN(page) || page < 1) {
    page = 1
  } else if (page > totalPages.value) {
    page = totalPages.value
  }
  currentPage.value = page
}

// 批量操作
const batchOperation = (operation) => {
  if (selectedArticleIds.value.length === 0) return
  
  if (operation === 'delete') {
    deleteBatch.value = true
    deleteArticleIds.value = [...selectedArticleIds.value]
    deleteDialogVisible.value = true
  } else if (operation === 'export') {
    // 模拟导出操作
    alert(`已导出 ${selectedArticleIds.value.length} 篇文章`)
  }
}

// 显示新增文章对话框
const showAddArticleDialog = () => {
  isEditMode.value = false
  currentEditingId.value = null
  articleDialogVisible.value = true
  
  // 重置表单
  Object.assign(articleForm, {
    title: '',
    siteId: filters.siteId || '',
    categoryId: '',
    authorId: '',
    coverImage: '',
    summary: '',
    content: '',
    status: 'draft',
    isTop: false,
    isRecommend: false,
    allowComment: true,
    seoTitle: '',
    seoKeywords: '',
    seoDescription: ''
  })
}

// 显示编辑文章对话框
const showEditArticleDialog = (id) => {
  const article = articles.value.find(a => a.id === id)
  if (!article) return
  
  isEditMode.value = true
  currentEditingId.value = id
  articleDialogVisible.value = true
  
  // 填充表单
  Object.assign(articleForm, {
    title: article.title,
    siteId: article.siteId,
    categoryId: article.categoryId,
    authorId: article.authorId,
    coverImage: article.coverImage,
    summary: article.summary,
    content: article.content,
    status: article.status,
    isTop: article.isTop,
    isRecommend: article.isRecommend,
    allowComment: article.allowComment,
    seoTitle: article.seoTitle,
    seoKeywords: article.seoKeywords,
    seoDescription: article.seoDescription
  })
}

// 关闭文章对话框
const closeArticleDialog = () => {
  articleDialogVisible.value = false
}

// 保存文章
const saveArticle = () => {
  // 简单验证
  if (!articleForm.title) {
    alert('请输入文章标题')
    return
  }
  
  if (!articleForm.siteId) {
    alert('请选择所属站点')
    return
  }
  
  if (!articleForm.categoryId) {
    alert('请选择所属栏目')
    return
  }
  
  if (!articleForm.content) {
    alert('请输入文章内容')
    return
  }
  
  if (isEditMode.value) {
    // 编辑现有文章
    const index = articles.value.findIndex(a => a.id === currentEditingId.value)
    if (index !== -1) {
      const author = authors.value.find(auth => auth.id == articleForm.authorId)
      const updated = {
        ...articles.value[index],
        title: articleForm.title,
        siteId: articleForm.siteId,
        categoryId: articleForm.categoryId,
        authorId: articleForm.authorId,
        authorName: author ? author.name : articles.value[index].authorName,
        authorAvatar: author ? author.avatar : articles.value[index].authorAvatar,
        coverImage: articleForm.coverImage,
        summary: articleForm.summary,
        content: articleForm.content,
        status: articleForm.status,
        isTop: articleForm.isTop,
        isRecommend: articleForm.isRecommend,
        allowComment: articleForm.allowComment,
        seoTitle: articleForm.seoTitle,
        seoKeywords: articleForm.seoKeywords,
        seoDescription: articleForm.seoDescription,
        updateTime: new Date().toLocaleDateString(),
        // 如果状态变为已发布且之前未发布过，则设置发布时间
        publishTime: articleForm.status === 'published' && articles.value[index].status !== 'published' 
          ? new Date().toLocaleDateString() 
          : articles.value[index].publishTime
      }
      articles.value[index] = updated
    }
  } else {
    // 新增文章
    const newId = Math.max(...articles.value.map(a => a.id), 0) + 1
    const author = authors.value.find(auth => auth.id == articleForm.authorId)
    const now = new Date().toLocaleDateString()
    articles.value.push({
      id: newId,
      title: articleForm.title,
      categoryId: articleForm.categoryId,
      siteId: articleForm.siteId,
      authorId: articleForm.authorId || authors.value[0].id,
      authorName: author ? author.name : authors.value[0].name,
      authorAvatar: author ? author.avatar : authors.value[0].avatar,
      coverImage: articleForm.coverImage,
      summary: articleForm.summary,
      content: articleForm.content,
      status: articleForm.status,
      isTop: articleForm.isTop,
      isRecommend: articleForm.isRecommend,
      allowComment: articleForm.allowComment,
      viewCount: 0,
      commentCount: 0,
      createTime: now,
      updateTime: now,
      publishTime: articleForm.status === 'published' ? now : null,
      seoTitle: articleForm.seoTitle,
      seoKeywords: articleForm.seoKeywords,
      seoDescription: articleForm.seoDescription
    })
  }
  
  // 关闭对话框
  articleDialogVisible.value = false
  alert(isEditMode.value ? '文章更新成功' : '文章创建成功')
}

// 确认删除文章
const confirmDeleteArticle = (id) => {
  deleteBatch.value = false
  deleteArticleIds.value = [id]
  deleteDialogVisible.value = true
}

// 确认删除
const deleteConfirmed = () => {
  // 执行删除
  articles.value = articles.value.filter(article => !deleteArticleIds.value.includes(article.id))
  
  // 更新选中状态
  selectedArticleIds.value = selectedArticleIds.value.filter(id => !deleteArticleIds.value.includes(id))
  if (selectedArticleIds.value.length === 0) {
    selectAll.value = false
  }
  
  // 关闭对话框
  deleteDialogVisible.value = false
  alert(`已删除 ${deleteArticleIds.value.length} 篇文章`)
}

// 查看文章详情
const viewArticle = (id) => {
  // 实际项目中应跳转到文章详情页
  router.push(`/article-detail?id=${id}`)
}

// 预览文章
const previewArticle = (id) => {
  // 实际项目中应打开文章预览页面
  alert(`预览文章 ID: ${id}`)
}

// 处理站点变更
const handleSiteChange = () => {
  articleForm.categoryId = ''
}

// 辅助函数：获取指定站点的栏目
const getSiteCategories = (siteId) => {
  return categories.value.filter(cat => cat.siteId == siteId)
}

// 辅助函数：查找栏目名称
const findCategoryName = (id) => {
  const category = categories.value.find(cat => cat.id === id)
  return category ? category.name : '未知栏目'
}

// 辅助函数：获取栏目缩进
const getCategoryIndent = (level) => {
  return '　'.repeat(level) // 使用全角空格实现缩进
}

// 辅助函数：获取状态名称
const getStatusName = (status) => {
  const statusMap = {
    'draft': '草稿',
    'pending': '待审核',
    'published': '已发布',
    'rejected': '已驳回'
  }
  return statusMap[status] || '未知状态'
}

// 辅助函数：获取状态标签样式
const getStatusBadgeClass = (status) => {
  const classMap = {
    'draft': 'bg-gray-100 text-gray-600',
    'pending': 'bg-warning/10 text-warning',
    'published': 'bg-success/10 text-success',
    'rejected': 'bg-danger/10 text-danger'
  }
  return classMap[status] || 'bg-gray-100 text-gray-600'
}
</script>